package com.seelyn.ddvideo.spider;

import com.seelyn.ddvideo.event.SystemEventPublisher;
import com.seelyn.ddvideo.model.Video;
import com.seelyn.ddvideo.model.VideoPlayer;
import com.seelyn.ddvideo.service.VideoService;
import com.seelyn.ddvideo.utils.DownloadQueue;
import com.seelyn.ddvideo.utils.UrlInfo;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.util.StringUtils;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;

import java.util.Calendar;
import java.util.List;

/**
 * @author slacrey
 * @since 2017/6/11
 */
public class KuyunVideoInfoMovieProcessor implements PageProcessor {

    private String uploadSite;
    private String uploadDir;
    private SystemEventPublisher eventPublisher;
    private VideoService videoService;
    private Video video;
    private List<VideoPlayer> players;
    private String imgXpathString = "/html/body/div[@class*='warp']/div[1]/div/div/div[@class*='vodImg']/img";
    private String scoreXpathString = "/html/body/div[@class='warp']/div[@class='ibox']/div[@class='vod']/div[@class='vodBox']/div[@class='vodInfo']/div[@class='vodh']/label";
    private String targetDir;
    private String targetName;

    public KuyunVideoInfoMovieProcessor(SystemEventPublisher eventPublisher, VideoService videoService, Video video, String uploadDir, String uploadSite) {
        this.eventPublisher = eventPublisher;
        this.videoService = videoService;
        this.video = video;
        this.uploadDir = uploadDir;
        this.uploadSite = uploadSite;
    }

    private Site site = Site.me().setDomain("http://ziyuanpian.com")
            .setCharset("UTF-8")
            .setSleepTime(100)
            .setUserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31");

    @Override
    public void process(Page page) {

        Html body = page.getHtml();
        Selectable spanItems = body.xpath(imgXpathString);

        if (spanItems == null || spanItems.all().isEmpty()) {
            return;
        }

        Html imgHtml = Html.create(spanItems.get());
        Element imgElement = imgHtml.getDocument().body().child(0);
        String picUrl = imgElement.attr("src");
        if (StringUtils.isEmpty(picUrl)) {
            return;
        }

        if (!picUrl.startsWith("http://")) {
            picUrl = site.getDomain() + picUrl;
        }

        Float score = 3.0F;
        Selectable scoreItems = body.xpath(scoreXpathString);
        if (scoreItems != null && !scoreItems.all().isEmpty()) {
            Html scoreItemsHtml = Html.create(scoreItems.get());
            Element scoreElement = scoreItemsHtml.getDocument().body().child(0);
            String scoreStr = scoreElement.ownText();
            if (!StringUtils.isEmpty(scoreStr)) {
                score = Float.valueOf(scoreElement.ownText());
                video.setScore(score);
            }
        }

        Calendar calendar = Calendar.getInstance();
        targetName = calendar.getTimeInMillis() + picUrl.substring(picUrl.lastIndexOf("."));
        String targetNamePrefix = calendar.get(Calendar.YEAR) + "-" + calendar.get(Calendar.MONTH) + "-" + calendar.get(Calendar.DAY_OF_MONTH);
        targetDir = uploadDir + "/" + targetNamePrefix;

        Boolean link = false;
        Html inputHtml = null;
        Html playInfoHtml = null;
        String html22 = null;
        List<Selectable> selectables = body.$(".vodplayinfo").nodes();

        for (Selectable selectable : selectables) {
            html22 = selectable.get();
            if (html22.contains("播放类型：kuyun")) {

                playInfoHtml = Html.create(html22);

                this.players = video.getPlayers(FromSiteEnum.KUYUN);
                //清空以前存在的播放地址
                this.players.clear();

                video.setVid(targetName);
//                video.setPicUrl(uploadSite + "/" + targetNamePrefix + "/" + targetName);
                video.setPicUrl(picUrl);

                Video oldVideo = videoService.findVideoByTitle(video.getTitle());
                if (oldVideo != null) {
                    video.setId(oldVideo.getId());
                    video.setVideoFroms(oldVideo.getVideoFroms());
                }

                link = documentHandler(playInfoHtml.getDocument().body(), "播放类型：kuyun", "直接复制链接", false);
                if (!link) {
                    continue;
                }

                break;

            }
        }

    }


    private Boolean documentHandler(Element rootElement, String startWithStr, String endWithStr, boolean matchFlag) {
        Boolean exist = false;
        Elements listElement = rootElement.children();
        for (Element element : listElement) {
            if (!matchFlag && startWithStr.equals(element.ownText())) {
                matchFlag = true;
            }

            if (matchFlag) {

                Elements inputList = element.getElementsByTag("li");
                if (!inputList.isEmpty()) {
                    int order = 0;
                    VideoPlayer player;

                    if (video.getSubType() >= MovieSubTypeEnum.GUOCHANJU.ordinal() && video.getSubType() < MovieSubTypeEnum.DONGMAN.ordinal()) {
                        video.setMovieType(MovieTypeEnum.tv.ordinal());
                    } else if (video.getSubType() < MovieSubTypeEnum.GUOCHANJU.ordinal()) {
                        video.setMovieType(MovieTypeEnum.movie.ordinal());
                    } else {
                        video.setMovieType(MovieTypeEnum.cartoon.ordinal());
                    }

                    for (Element element1 : inputList) {

                        String text = element1.text();
                        String[] textArray = text.split("\\$");
                        String name = textArray[0];
                        String link = textArray[1];
                        order++;

                        player = new VideoPlayer();
                        player.setName(name);
                        player.setUrl(link);
                        player.setOrder(order);
                        this.players.add(player);

                        videoService.saveVideo(video);

                    }
//                    DownloadQueue.add(new UrlInfo(video.getPicUrl(), targetDir, targetName, video));
                    exist = true;
                    continue;
                }

                String val = element.attr("value");
                if (!StringUtils.isEmpty(val) && endWithStr.equals(val)) {
                    break;
                }

            } else {
                exist = documentHandler(element, startWithStr, endWithStr, matchFlag);
                if (exist) {
                    break;
                }
            }
        }
        return exist;
    }


    @Override
    public Site getSite() {
        return site;
    }

}
